import { Injectable, CanActivate, ExecutionContext,HttpStatus, HttpException} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import {Auth} from './auth'

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
}

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      throw new HttpException('登录失效',HttpStatus.UNAUTHORIZED);
    }
    const request = context.switchToHttp().getRequest();
    const authorization = request.get('Authorization')
    if(authorization === 'null'){
      throw new HttpException('登录失效',HttpStatus.UNAUTHORIZED);
    }
    const auth = new Auth();
    if(! await auth.decodeToken(authorization)){
      throw new HttpException('登录失效',HttpStatus.UNAUTHORIZED);
    }
    // admin:超级管理员， front:前端客服， lawyer:律师, general: 普通用户
    // if (roles[0] !== '*') {
    //   const userInfo = auth.getUserInfo(authorization);
    //   console.log('userInfo', userInfo)
    //   // if (roles.some(v => v === 'admin') && userInfo.role) {

    //   // }
    //   throw new HttpException('登录失效',HttpStatus.UNAUTHORIZED);
    // }
    return true;
  }
}









